import random
import requests
from PIL import Image, ImageDraw, ImageFont
from datetime import datetime


def generate_id_number():
    """
    生成身份证号码方法
    """
    # 1. 前6位：随机省市区（示例：110101=北京市东城区）
    area_code = "110101"
    # area_code = "441721"

    # 2. 中间8位：出生日期（1990-2000年）
    birth_date = f"19{random.randint(90, 99)}{random.randint(1, 12):02d}{random.randint(1, 28):02d}"
    date_obj = datetime.strptime(birth_date, '%Y%m%d').date()
    year = date_obj.year
    month = date_obj.month
    day = date_obj.day
    # 3. 顺序码（3位随机）
    sequence = f"{random.randint(0, 999):03d}"
    # 4. 前17位拼接
    id_17 = area_code + birth_date + sequence

    # 5. 计算校验位（ISO 7064:1983 MOD 11-2）
    factors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
    checksum_map = {0: '1', 1: '0', 2: 'X', 3: '9', 4: '8', 5: '7', 6: '6', 7: '5', 8: '4', 9: '3', 10: '2'}
    total = sum(int(id_17[i]) * factors[i] for i in range(17))
    checksum = checksum_map[total % 11]
    idNumber = id_17 + checksum
    return idNumber,year,month,day

def virtual_IDcard_photo(name):
    idNumber, year, month, day = generate_id_number()  # 获取生成的ID号码和日期
    # 打开图片文件
    image = Image.open('空白身份证.png')

    # 创建绘图对象
    draw = ImageDraw.Draw(image)

    # 设置字体和大小（注意：字体路径根据你的系统调整）
    font_path = "simhei.ttf"  # 比如宋体支持中文
    font = ImageFont.truetype(font_path, 22)

    # 要添加的文字内容
    texts = [f"{name}",f"{year}",f"{month}",f"{day}",f"{idNumber}"]

    # 文字位置列表 [姓名、年、月、日、身份证号码]
    positions = [(125, 110), (130, 198),(230, 198), (280, 198),(209,361)]  # 每个文本的位置

    # 文字颜色（RGB格式）
    text_color = (0, 0, 0)  # 黑色

    # 绘制每个文本到图片上
    for text, position in zip(texts, positions):
        draw.text(position, text, fill=text_color, font=font)
    # 保存或显示结果
    image.save(f"{name}"+'人像面虚拟身份证.png')
    # image.show()

if __name__ == '__main__':
    name = input("输入姓名")
    virtual_IDcard_photo(name)